<?php
// -----------------------------------------------------
// Created by : php-task
// -----------------------------------------------------
// User: tf <1096392101@qq.com>
// -----------------------------------------------------
declare (strict_types=1);

namespace Gao\Task\ipc;


//共享内存
trait SharedMemory
{
    //key 值
    protected $key;

    //共享内存
    protected $shm_id;

    public function memory_init()
    {
        // Get the file token key
        $key = ftok(__DIR__, 'a');

        // 创建一个共享内存
        $this->shm_id = shm_attach($key, 1024, 777); // resource type

        if ($this->shm_id === false) {
            die('Unable to create the shared memory segment');
        }

        return $this->shm_id;
    }

    // 设置值
    public function setValue($val)
    {
        shm_put_var($this->shm_id, $this->key, $val);
    }

    // 获取key=>val
    public function getValue()
    {
        return shm_get_var($this->shm_id,  $this->key);
    }

    //判断是否存在key
    public function hasValue(): bool
    {
        return shm_has_var($this->shm_id,  $this->key);
    }

    //删除一个key
    public function delKey(): bool
    {
        return shm_remove_var($this->shm_id, $this->key);
    }

    //删除共享内存
    public function del(): bool
    {
        #从系统中移除
        return shm_remove($this->shm_id);
    }

    //关闭和共享内存的连接
    public function close(): bool
    {
        return shm_detach($this->shm_id);
    }

}